//获取当前缓存数据大小
export function getCashSzie(callback: Function) {
  let cashSize: string = "0";
  // #ifdef  APP-PLUS
  plus.cache.calculate(function (size: string) {
    let sizeCache = parseInt(size);
    if (sizeCache == 0) {
      cashSize = "0";
    } else if (sizeCache < 1024) {
      cashSize = sizeCache + "B";
    } else if (sizeCache < 1048576) {
      cashSize = (sizeCache / 1024).toFixed(2) + "KB";
    } else if (sizeCache < 1073741824) {
      cashSize = (sizeCache / 1048576).toFixed(2) + "MB";
    } else {
      cashSize = (sizeCache / 1073741824).toFixed(2) + "GB";
    }
    callback(cashSize);
  });

  // #endif
  // #ifndef APP-PLUS
  const storageInfo = uni.getStorageInfoSync();
  cashSize = formatCashUnit(storageInfo.currentSize);
  callback(cashSize);
  // #endif
}

export function formatCashUnit(kbNum: number, decimals = 2) {
  if (kbNum === 0) {
    return "0";
  }
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ["KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  const i = Math.floor(Math.log(kbNum) / Math.log(k));
  const result = parseFloat(kbNum / Math.pow(k, i) + "").toFixed(dm);
  return result + sizes[i];
}

// 清理缓存
export function clearCache(callBack: Function) {
  // #ifdef APP-PLUS
  let os = plus.os.name;
  if (os == "Android") {
    let main = plus.android.runtimeMainActivity();
    let sdRoot = main.getCacheDir();
    let files = plus.android.invoke(sdRoot, "listFiles");
    let len = files.length;
    for (let i = 0; i < len; i++) {
      let filePath = "" + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径
      plus.io.resolveLocalFileSystemURL(
        filePath,
        function (entry) {
          if (entry.isDirectory) {
            entry.removeRecursively(
              function (entry) {
                //递归删除其下的所有文件及子目录
                uni.showToast({
                  icon: "none",
                  title: "缓存清理完成",
                  duration: 2000
                });
                getCashSzie((size: string) => {
                  callBack(size);
                }); // 重新计算缓存
              },
              function (e) {
                console.log(e.message);
              }
            );
          } else {
            entry.remove();
          }
        },
        function (e) {
          console.log("文件路径读取失败");
        }
      );
    }
  } else {
    // ios
    plus.cache.clear(function () {
      uni.showToast({
        icon: "none",
        title: "缓存清理完成",
        duration: 2000
      });
      getCashSzie((size: string) => {
        callBack(size);
      });
    });
  }
  // #endif
  // #ifndef APP-PLUS
  uni.clearStorageSync();
  uni.showToast({
    icon: "none",
    title: "缓存清理完成",
    duration: 2000
  });
  getCashSzie((size: string) => {
    callBack(size);
  });
  // #endif
}
